package com.hgsoft.pubsv.component.apifilter.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 获取客户端IP
 * @author saint
 *
 */
@Slf4j
public class IPUtil {

	/**
	 * 客户端真实IP地址的方法一：
	 */
	public static String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

	/**
	 * 客户端真实IP地址的方法二：
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = "";
		if (request != null) {
			ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("X-Real-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		}
		return ip;
	}
	
	/**
	 * 获取head
	 * @param request
	 * @param headName
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String getHeader(HttpServletRequest request, String headName) {
		String value = request.getHeader(headName);
		return (StringUtils.isNotBlank(value) && !"unknown".equalsIgnoreCase(value)) ? value : "";
	}

	/**
	 * IP地址区间方式的配置,多个区间用逗号或分好隔开；
	 * 
	 * @param remoteAddr
	 * @param allowIPRange
	 * @return
	 */
	public static boolean checkIp(String remoteAddr, String allowIPRange) {
		if (null != allowIPRange && StringUtils.isNotBlank(allowIPRange)) {
			log.debug("remoteAddr:{}, allowIPRange: {} ", remoteAddr, allowIPRange);
			List<String> allowList = new ArrayList<String>();
			// 先进行每一段的分割
			String[] allowIPRanges = allowIPRange.split(",|;");

			if (allowIPRanges.length > 0) {
				// 对每一段进行遍历
				for (String allowRanges : allowIPRanges) {
					if (allowRanges != null && !"".equals(allowRanges.trim())) {
						// 对该段的ip进行解析
						String[] ips = allowRanges.split("-");
						if (ips.length > 0 && ips.length < 3) {
							String from = ips[0];// 得到该段的起始ip
							String to = ips[1]; // 得到该段的结束ip

							// 获取该ip段地址的前三段，因为起始和结束的ip的前三段一样
							String share = from.substring(0, from.lastIndexOf(".") + 1);

							// 获取该ip段的起始ip的最后一段
							int start = Integer.parseInt(from.substring(from.lastIndexOf(".") + 1, from.length()));
							// 获取该ip段的结束ip的最后一段
							int end = Integer.parseInt(to.substring(to.lastIndexOf(".") + 1, to.length()));
							for (int i = start; i <= end; i++) {
								String ip = share + String.valueOf(i);
								allowList.add(ip);
							}
						} else {
							throw new RuntimeException("配置有错，请检查！");
						}
					}

				}
			}

			// 如果allowList为空,则认为没做限制,不为空则检查是否限制
			if (allowList.size() == 0 || allowList == null) {
				return true;
			} else {
				Boolean flag = false; // 访问标志，默认为false，限制访问
				// 进行逐个检查
				for (String regex : allowList) {
					if (remoteAddr.matches(regex)) {
						// ip没被限制，正常访问
						flag = true; // 置为true，表示不限制访问
						break;
					}
				}
				return flag;
			}
		}
		return true;
	}

}
